﻿//Copyright 2011 - Jonathan Allen

using System;
using System.Windows;
using System.Globalization;
using System.Diagnostics.Contracts;

namespace Granite.Xaml.Converters
{
    /// <summary>
    /// Use this converter to show a control when the bound value is null or an empty string.
    /// For WPF, the parameter is used to choose between Collapsed and Hidden. The default is Collapsed.
    /// </summary>
	public class NullToVisibleConverter : OneWayMarkupValueConverter<NullToVisibleConverter>
    {
		/// <summary>
		/// 
		/// </summary>
		/// <param name="value">Any nullable type</param>
		/// <param name="targetType">Visibility</param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns></returns>
        [Pure]
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var newVisibility = Visibility.Collapsed;

#if !SILVERLIGHT
			if (parameter is Visibility)
				newVisibility = (Visibility)parameter;
			else
			{
				var stringParameter = parameter as String;
				if (stringParameter != null && stringParameter.ToUpperInvariant() == "HIDDEN")
					newVisibility = Visibility.Hidden;
			}
#endif

			if (value == null)
				return Visibility.Visible;

#if !WINDOWS_PHONE
			if (value is String && String.IsNullOrWhiteSpace((string)value))
				return Visibility.Visible;
#else
            if (value is String && Granite.StringUtilities.IsNullOrWhiteSpace((string)value))
                return Visibility.Visible;
#endif

			return newVisibility;
		}

    }
}
